package com.sikaryofficial.backend.service.address;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sikaryofficial.backend.config.CountryAgeLimitConfig;
import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.domain.dto.resp.CountryGeoDTO;
import com.sikaryofficial.backend.domain.entity.Country;
import com.sikaryofficial.backend.service.ICountryService;
import com.sikaryofficial.backend.service.IGadmCountryGeoService;
import com.sikaryofficial.common.redis.service.RedisService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : qinjinyuan
 * @desc : 国家编码缓存服务
 * @date : 2023/11/03 17:11
 */
@Component
@Slf4j
public class CountryCacheService {
    @Autowired
    private IGadmCountryGeoService gadmCountryGeoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CountryAgeLimitConfig config;
    @Autowired
    private ICountryService countryService;

    /**
     * 国家编码缓存服务 (数据预加载)
     *
     * @return
     */
    public void loadAllCountry() {
        List<CountryGeoDTO> countryGeoDTOS = gadmCountryGeoService.selectAllCountryList();
        if (Collections.isEmpty(countryGeoDTOS)) {
            return;
        }
        // 添加政策年龄字段
        countryGeoDTOS.forEach(item-> item.setAge(config.getAgeByCode(item.getIsoCountryCode())));
        // 数据排序
        countryGeoDTOS = countryGeoDTOS.stream().sorted(Comparator.comparing(CountryGeoDTO::getCountry)).collect(Collectors.toList());
        log.info("load Country code size :{}", countryGeoDTOS.size());
        // 清除
        redisService.deleteObject(RedisCacheKey.COUNTRY_CODE_LIST_CACHE);
        // 添加
        redisService.setCacheList(RedisCacheKey.COUNTRY_CODE_LIST_CACHE, countryGeoDTOS);
    }

    public void loadAllCountryCode() {
        List<Country> countryList = countryService.list(new LambdaQueryWrapper<Country>()
                .eq(Country::getDeletedVersion, 0L)
        );
        if (Collections.isEmpty(countryList)) {
            return;
        }
        // 清除
        redisService.deleteObject(RedisCacheKey.COUNTRY_SHORT_CODE_HASH_CACHE);
        // 添加
        countryList.forEach(item -> {
            if (CharSequenceUtil.isNotBlank(item.getCountryShortCode())) {
                redisService.setCacheMapValue(RedisCacheKey.COUNTRY_SHORT_CODE_HASH_CACHE, item.getCountryShortCode(), item);
            }
        });
    }

    public Country getCountryByShortCode(String shortCode) {
        if(CharSequenceUtil.isBlank(shortCode)){
            return null;
        }
        return redisService.getCacheMapValue(RedisCacheKey.COUNTRY_SHORT_CODE_HASH_CACHE, shortCode);
    }
}
